package logic

import (
	"context"
	"encoding/json"
	"fmt"
	"shuqi-novel/models/cache"
	"shuqi-novel/models/mysql"
	"time"

	"shuqi-novel/novelrpc/internal/svc"
	"shuqi-novel/novelrpc/novelrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type NovelListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewNovelListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *NovelListLogic {
	return &NovelListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *NovelListLogic) NovelList(in *novelrpc.NovelListRequest) (*novelrpc.NovelListResponse, error) {
	// todo: add your logic here and delete this line
	offset := (in.Page - 1) * in.Size

	key := fmt.Sprintf("novelList%d%d%d", in.UserId, in.Page, in.Size)

	var novels []mysql.Novel
	result, _ := cache.Rdb.Get(l.ctx, key).Result()

	if result == "" {

		mysql.DB.Debug().Where("user_id = ?", in.UserId).Offset(int(offset)).Limit(int(in.Size)).Find(&novels)

		marshal, _ := json.Marshal(novels)

		cache.Rdb.Set(l.ctx, key, marshal, time.Minute*30)

	} else {
		json.Unmarshal([]byte(result), &novels)
	}

	var novelList []*novelrpc.NovelList
	for _, novel := range novels {
		list := novelrpc.NovelList{
			Title:   novel.Title,
			Image:   novel.Image,
			UserId:  novel.UserId,
			NovelId: int64(novel.ID),
		}

		novelList = append(novelList, &list)
	}

	return &novelrpc.NovelListResponse{
		List: novelList,
	}, nil
}
